package com.imooc.router.runter.runtime

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log

/**
 *@author: xiaosy
 *时间: 2024/11/14
 *@Description: 由于这个类是编译之后生成的类，所以不能直接使用
 * 只能通过反射的方式使用
 *@Version: 1.0
 **/
object Router {
    private const val TAG = "Router"

    private const val GENERATED_MAPPING = "com.imooc.router.mapping.generated.RouterMapping"

    private val mapping: HashMap<String, String> = HashMap()

    fun init() {
        try {
            val clazz = Class.forName(GENERATED_MAPPING)
            val method = clazz.getMethod("get")
            val allMapping = method.invoke(null) as Map<String, String>
            if (allMapping.isNotEmpty()) {
                Log.i(TAG, "init: get all mapping:")
                allMapping.onEach {
                    Log.i(TAG, "${it.key} -> ${it.value}")
                }
                mapping.putAll(allMapping)
            }
        } catch (e: Throwable) {
            //init: error while init router: com.imooc.router.mapping.generated.RouterMapping.class
            e.printStackTrace()
            Log.e(TAG, "init: error while init router: $e")
        }

    }

    fun go(context: Context, url: String) {
        val uri = Uri.parse(url)
        val scheme = uri.scheme
        val host = uri.host
        val path = uri.path
        var targetActivityClass = ""
        mapping.onEach {
            val ruri = Uri.parse(it.key)
            val rscheme = ruri.scheme
            val rhost = ruri.host
            val rpath = ruri.path
            if (rscheme == scheme && rhost == host && rpath == path) {
                targetActivityClass = it.value
            }
        }
        if(targetActivityClass.isEmpty()) {
            Log.e(TAG, " go: no destination found.")
            return
        }
        val bundle = Bundle()
        val query = uri.query
        query?.let {
            Log.i(TAG, "query: $it")
            if(it.length >= 3) {
                val args = it.split("&")
                args.onEach { arg ->
                    val splits = arg.split("=")
                    bundle.putString(splits[0], splits[1])
                }
            }
        }

        try {
            Log.i(TAG, "targetActivityClass: $targetActivityClass")
            val activity = Class.forName(targetActivityClass)
            val intent = Intent(context, activity)
            intent.putExtras(bundle)
            context.startActivity(intent)
        }catch (e: Throwable){
            Log.e(TAG, "go: error while start Activity: $targetActivityClass. e=$e")
        }
    }
}